/* eslint-disable node/prefer-global/process */
import path from 'node:path'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import postPx2Rem from 'postcss-plugin-px2rem'
import UnoCSS from 'unocss/vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import vueJsx from '@vitejs/plugin-vue-jsx'

/** @type {import('vite').UserConfig} */
export default defineConfig(({ mode }) => {
  // 获取 .env 环境配置文件
  const env = loadEnv(mode, process.cwd())
  return {
    plugins: [
      vueJsx(),
      vue(),
      UnoCSS(),
      AutoImport({
        // 自动导入 vue 相关函数，如：ref、reactive 等
        imports: ['vue', '@vueuse/core'],
        eslintrc: {
          enabled: true,
          filepath: './.eslintrc-auto-import.json',
          globalsPropValue: true,
        },
        resolvers: [
          // 自动导入 Element Plus 相关函数，如：ElMessage
          ElementPlusResolver(),
        ],
        // 是否在 vue 模板中自动导入
        vueTemplate: true,
        // 自动导入组件类型声明文件位置，默认根目录；false关闭自动生成
        dts: path.resolve(
          path.resolve(__dirname, 'src'),
          'types',
          'auto-imports.d.ts',
        ),
      }),
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]',
      }),
      Components({
        resolvers: [
          // 自动导入 Element Plus 组件
          ElementPlusResolver(),
        ],
        dts: path.resolve(
          path.resolve(__dirname, 'src'),
          'types',
          'components.d.ts',
        ),
      }),
    ],
    // 本地反向代理解决浏览器跨域限制
    server: {
      host: '0.0.0.0', // ← 新增内容 ←
      port: 8899,
      open: false,
      proxy: {
        [env.VITE_APP_URL]: {
          target: env.VITE_APP_BASE_API,
          changeOrigin: true,
          rewrite: (path: string) =>
            path.replace(new RegExp(`^${env.VITE_APP_URL}`), ''),
        },
        // '/ws2': {
        //   target: env.VITE_WS_URL,
        //   changeOrigin: true,
        //   ws: true,
        //   rewrite: (path: string) => path.replace(/^\/ws2/, ''),
        // },
      },
    },

    resolve: {
      alias: {
        '@': path.resolve('./src'), // 相对路径使用@代替 src
      },
    },
    build: {
      outDir: 'dist',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
      assetsDir: 'assets', // 指定静态资源存放路径
      sourcemap: true, // 是否构建source map 文件
    },
    css: {
      devSourcemap: true,
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          additionalData: '',
        },
      },
      postcss: {
        plugins: [
          postPx2Rem({
            rootValue: 192, // 换算基数， 1rem=192px
            unitPrecision: 6, // 允许REM单位增长到的十进制数字，其实就是精度控制
            // propWhiteList: [], // 默认值是一个空数组，这意味着禁用白名单并启用所有属性。
            // propBlackList: [], // 黑名单
            // exclude:false,  //默认false，可以（reg）利用正则表达式排除某些文件夹的方法，例如/(node_module)/ 。如果想把前端UI框架内的px也转换成rem，请把此属性设为默认值
            // selectorBlackList: [], //要忽略并保留为px的选择器
            // ignoreIdentifier: false, //（boolean/string）忽略单个属性的方法，启用ignoreidentifier后，replace将自动设置为true。
            // replace: true, // （布尔值）替换包含REM的规则，而不是添加回退。
            // mediaQuery: false, //（布尔值）允许在媒体查询中转换px
            // minPixelValue: 0  //设置要替换的最小像素值(3px会被转rem)。 默认 0
          }),
          // postcssRtlcss({})
        ],
      },
    },
    // 预构建
    optimizeDeps: {
      entries: 'index.html',
      include: [
        'vue',
        'vue-router',
        'pinia',
        'axios',
        'element-plus/es/components/form/style/css',
        'element-plus/es/components/form-item/style/css',
        'element-plus/es/components/button/style/css',
        'element-plus/es/components/input/style/css',
        'element-plus/es/components/input-number/style/css',
        'element-plus/es/components/switch/style/css',
        'element-plus/es/components/upload/style/css',
        'element-plus/es/components/menu/style/css',
        'element-plus/es/components/col/style/css',
        'element-plus/es/components/icon/style/css',
        'element-plus/es/components/row/style/css',
        'element-plus/es/components/tag/style/css',
        'element-plus/es/components/dialog/style/css',
        'element-plus/es/components/loading/style/css',
        'element-plus/es/components/radio/style/css',
        'element-plus/es/components/radio-group/style/css',
        'element-plus/es/components/popover/style/css',
        'element-plus/es/components/scrollbar/style/css',
        'element-plus/es/components/tooltip/style/css',
        'element-plus/es/components/dropdown/style/css',
        'element-plus/es/components/dropdown-menu/style/css',
        'element-plus/es/components/dropdown-item/style/css',
        'element-plus/es/components/sub-menu/style/css',
        'element-plus/es/components/menu-item/style/css',
        'element-plus/es/components/divider/style/css',
        'element-plus/es/components/card/style/css',
        'element-plus/es/components/link/style/css',
        'element-plus/es/components/breadcrumb/style/css',
        'element-plus/es/components/breadcrumb-item/style/css',
        'element-plus/es/components/table/style/css',
        'element-plus/es/components/tree-select/style/css',
        'element-plus/es/components/table-column/style/css',
        'element-plus/es/components/select/style/css',
        'element-plus/es/components/option/style/css',
        'element-plus/es/components/pagination/style/css',
        'element-plus/es/components/tree/style/css',
        'element-plus/es/components/alert/style/css',
        'element-plus/es/components/message/style/css',
        'element-plus/es/components/message-box/style/css',
        'element-plus/es/components/rate/style/css',
        'element-plus/es/components/date-picker/style/css',
        'element-plus/es/components/collapse/style/css',
        'element-plus/es/components/collapse-item/style/css',
        'element-plus/es/components/checkbox-group/style/css',
        'element-plus/es/components/checkbox/style/css',
        'element-plus/es/components/cascader/style/css',
        'element-plus/es/components/time-picker/style/css',
        'element-plus/es/components/tabs/style/css',
        'element-plus/es/components/tab-pane/style/css',
        'element-plus/es/components/infinite-scroll/style/css',
        '@vueuse/core',
        'echarts',
        'vue-i18n',
        'js-cookie',
      ],
    },
  }
})
